/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.delivery.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.model.*;
import com.yami.shop.dao.OrderItemMapper;
import com.yami.shop.dao.OrderRefundMapper;
import com.yami.shop.delivery.comment.dao.DeliveryOrderMapper;
import com.yami.shop.delivery.comment.model.DeliveryOrder;
import com.yami.shop.delivery.comment.model.DeliveryOrderItem;
import com.yami.shop.delivery.comment.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.comment.service.DeliveryOrderItemService;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.NotifyTemplateService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 *
 *
 * @author lhd
 * @date 2020-04-22 15:46:05
 */
@Service
@AllArgsConstructor
public class DeliveryOrderServiceImpl extends ServiceImpl<DeliveryOrderMapper, DeliveryOrder> implements DeliveryOrderService {

    private final DeliveryOrderMapper deliveryOrderMapper;
    private final DeliveryOrderItemService deliveryOrderItemService;
    private final OrderService orderService;
    private final NotifyTemplateService notifyTemplateService;
    private final DeliveryService deliveryService;
    private final UserAddrOrderService userAddrOrderService;
    private final OrderItemMapper orderItemMapper;
    private final ApplicationContext applicationContext;
    private final OrderRefundMapper orderRefundMapper;
    private final MapperFacade mapperFacade;
    /**
    /**
     * 生成物流信息及保存物流与订单关联
     * @param deliveryOrderParam 物流信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDeliveriesInfo(DeliveryOrderItemParam deliveryOrderParam) {
        boolean isDelivery = true;
        List<OrderItem> selectOrderItems = deliveryOrderParam.getSelectOrderItems();
        selectOrderItems.forEach(i->i.setDvyType(deliveryOrderParam.getDeliveryType()));
        String orderNumber = deliveryOrderParam.getOrderNumber();
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderNumber));
        if (deliveryOrderParam.getDeliveryType() == 1){
            //校验数量及获取发货的总数
            int prodNumSum = checkDelivery(selectOrderItems);
            DeliveryOrder deliveryOrder = new DeliveryOrder();
            deliveryOrder.setOrderNumber(deliveryOrderParam.getOrderNumber());
            deliveryOrder.setDvyId(deliveryOrderParam.getDvyId());
            deliveryOrder.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
            deliveryOrder.setCreateTime(new Date());
            deliveryOrder.setStatus(1);
            deliveryOrder.setProductNums(prodNumSum);
            //保存订单物流信息
            save(deliveryOrder);
            //保存需要添加的关联信息
            List<DeliveryOrderItem> addDeliveries = new ArrayList<>();
            for (OrderItem selectOrderItem : selectOrderItems) {
                DeliveryOrderItem deliveryOrderItem = new DeliveryOrderItem();
                deliveryOrderItem.setOrderItemId(selectOrderItem.getOrderItemId());
                deliveryOrderItem.setProdCount(selectOrderItem.getChangeNum());
                deliveryOrderItem.setOrderDeliveryId(deliveryOrder.getOrderDeliveryId());
                addDeliveries.add(deliveryOrderItem);
            }
            if(CollectionUtils.isNotEmpty(addDeliveries)){
                deliveryOrderItemService.saveBatch(addDeliveries);
            }
        }
        orderItemMapper.updateByDeliveries(selectOrderItems);
        //判断是否发货完成
        List<OrderItem> orderItems = null;
        if (Objects.isNull(order.getRefundStatus())){
            orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderNumber));
        }else {
            orderItems = orderItemMapper.getListByOrderNumber(orderNumber);
        }
        // 有多个商品的订单， 有退款记录的，并且有退款成功的单个商品，
        // 其余的商品都是发货完成的订单，改成发货状态
        // 在退款处理的时候将状态改为0即可
        for (OrderItem orderItem : orderItems) {
            if (orderItem.getStatus() != 0) {
                isDelivery = false;
            }
        }
        //修改为发货状态
        if(isDelivery){
            Date date = new Date();
            order.setStatus(OrderStatus.CONSIGNMENT.value());
            order.setUpdateTime(date);
            order.setDvyTime(date);
            //判断是无需物流还是快递发货
            order.setDvyType(deliveryOrderParam.getDeliveryType());
            // 如果是无需快递，则判断该订单是否包含有物流的项，若有物流则配送类型为快递配送，没有物流则不变
            if (Objects.equals(order.getDvyType(), DvyType.NOT_DELIVERY.value())) {
                List<DeliveryOrder> deliveryOrders = list(new LambdaQueryWrapper<DeliveryOrder>().eq(DeliveryOrder::getOrderNumber, orderNumber));
                if (!CollectionUtils.isEmpty(deliveryOrders)){
                    order.setDvyType(1);
                }
            }
            orderService.updateById(order);
            String dvyName = "店铺同城配送";
            order.setDvyFlowId("同城配送");
            // 消息推送-发货提醒
            if(Objects.equals(order.getDvyType(), DvyType.DELIVERY.value())){
                Delivery delivery = deliveryService.getById(deliveryOrderParam.getDvyId());
                order.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
                dvyName = "";
                if(Objects.nonNull(delivery) && delivery.getDvyName() != null){
                    dvyName = delivery.getDvyName();
                }
            }
            notifyTemplateService.sendNotifyOfDelivery(order,dvyName, SendType.DELIVERY);
        }
    }


    /**
     * 修改物流信息
     * @param deliveryOrders 物流修改的信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderDeliveries(List<DeliveryOrder> deliveryOrders) {
        updateBatchById(deliveryOrders);
    }

    @Override
    public List<DeliveryOrder> getAndDeliveryItemInfo(String orderNumber) {
        return deliveryOrderMapper.getAndDeliveryItemInfo(orderNumber);
    }

    @Override
    public List<DeliveryOrder> listDetailDelivery(String orderNumber) {
        return deliveryOrderMapper.listDetailDelivery(orderNumber);
    }

    /**
     * 校验可发货数量并返回总数
     * @param selectOrderItems 选择发货的订单项
     */
    private int checkDelivery(List<OrderItem> selectOrderItems) {
        //获取发货总数
        int prodNumSum = 0;
        for (OrderItem selectOrderItem : selectOrderItems) {
            prodNumSum += selectOrderItem.getChangeNum();
        }
        return prodNumSum;
    }
}
